# coding: utf8

from ops.devops.utils.util_config import get_config
from ops.chatbot.utils.send_msg import SendMessage
from huaweicloudsdkdns.v2 import *
from ops.chatbot.utils.utils import get_kv_by_list
from ops.devops.utils.utils_domain import DomainOp


conf = get_config('cloud')


# ref命令时执行如下函数
def domain(*args, **kwargs):
    """
    增加域名解析
    :param args:
    :param kwargs:
    :return:
    """

    webhook = kwargs.get("webhook")
    if (args.__len__() >= 1 and args[0] == 'help') or args.__len__() == 0:
        msg = '添加域名解析记录，用法: domain domain_name domain_type records_list'
        SendMessage.send_md(webhook, msg)
    domain_name = args[0]
    domain_type = args[1]
    records_list = args[2:]

    msg = f'debug:输入信息{args}'

    client = DomainOp.create_client()
    zones = DomainOp.list_zones(client)
    if not zones:
        print('获取endpoint={0}的区域失败，请检查'.format(conf.get('domain_endpoint')))
    name_id = get_kv_by_list(zones, 'name', 'id')
    zone_id = name_id.get(conf.get('domain_root'))
    res = DomainOp.create_record_set(client, zone_id, domain_name, domain_type, records_list)
    # 发送钉钉通知
    SendMessage.send_md(webhook, res.get('msg'))
